#!/usr/bin/python
# author dennis
# 2022年06月19日
import socket
import struct


class Client:
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

    def tcp_connect(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect((self.ip, self.port))

    def send_train(self, train_head_bytes):
        train_head = struct.pack('I', len(train_head_bytes))
        self.client.send(train_head + train_head_bytes)

    def recv_train(self):
        train_head_bytes = self.client.recv(4)
        train_head = struct.unpack('I', train_head_bytes)
        return self.client.recv(train_head[0])

    def do_ls(self):
        data = self.recv_train().decode('utf8')
        print(data)

    def do_cd(self):
        data = self.recv_train().decode('utf8')
        print(data)

    def do_pwd(self):
        data = self.recv_train().decode('utf8')
        print(data)

    def do_rm(self, command):
        file_name = command.split()[1]
        self.send_train(file_name.encode('utf8'))
        data = self.recv_train().decode('utf8')
        print(data)

    def do_gets(self, command):
        file_name = command.split()[1]
        f = open('【接收】' + file_name, 'wb+')
        file_content = self.recv_train()
        f.write(file_content)
        f.close()
        data = self.recv_train().decode('utf8')
        print(data)

    def do_puts(self, command):
        file_name = command.split()[1]
        self.send_train(file_name.encode('utf8'))
        f = open(file_name, 'rb+')
        f_content = f.read()
        self.send_train(f_content)
        f.close()
        data = self.recv_train().decode('utf8')
        print(data)

    def deal_command(self):
        while True:
            command = input()
            self.send_train(command.encode('utf8'))
            if command[:2] == 'ls':
                self.do_ls()
            elif command[:2] == 'cd':
                self.do_cd()
            elif command[:3] == 'pwd':
                self.do_pwd()
            elif command[:2] == 'rm':
                self.do_rm(command)
            elif command[:4] == 'gets':
                self.do_gets(command)
            elif command[:4] == 'puts':
                self.do_puts(command)
            else:
                print('WRONG COMMAND!')


def main():
    c = Client('192.168.1.2', 2000)
    c.tcp_connect()
    c.deal_command()


if __name__ == '__main__':
    main()
